package com.five.admin.config;

import com.five.admin.redis.RedisKeyExpirationListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.concurrent.Executors;

@Configuration
@Slf4j
public class RedisKeyExpirationConfig {

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory,
            RedisKeyExpirationListener keyExpirationListener) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);

        // 监听所有数据库的键过期事件
        container.addMessageListener(keyExpirationListener,new PatternTopic("__keyevent@*__:expired"));

        // 设置任务执行器
        container.setTaskExecutor(Executors.newFixedThreadPool(4));
        container.setErrorHandler(e ->
                log.error("Redis监听错误", e));

        return container;
    }
}